<template>
  <div class="compoents-chart-box" >
    <div class="view-box" :style="'width:' + chartBoxWidth + 'px'">
      <div class="svg-chart-box">
        <!-- <svg width="100%" height="100%" viewBox="0 0 500 200" preserveAspectRatio="none"> -->
        <svg width="100%" height="100%" preserveAspectRatio="none">
          <g v-for="externalPoint in externalPoints" :class="{'selected': selectedPathIndex === $index}">
            <path v-show="selectedPathIndex !== $index" :d="paths[$index]" :stroke="externalPoint.color" @click="selectedPathEvent($index)"></path>
            <template v-for="pointCoordinate in pointCoordinates">
              <circle class="circle" v-for="point in pointCoordinate" :cx="point.x" :cy="point.y" r="8" :fill="pathColor(pointCoordinate)"/>
            </template>
          </g>
          <g v-for="externalPoint in externalPoints" :class="{'selected': selectedPathIndex === $index}">
            <path v-show="selectedPathIndex === $index" :d="paths[$index]" :stroke="externalPoint.color"></path>
          </g>
        </svg>
        <div class="points-box" v-show="true">
          <div class="point-touch" v-for="point in selectedPathCoordinates" :style="'left:' +point.x+ 'px;top:' +point.y+ 'px;'"  :class="{'selected': selectedPointIndex === point.index}" @click="selectedPointEvent(point.index)">
            <div class="point" :style="'background:' + externalPoints[selectedPathIndex].color">
              <div v-show="selectedPointIndex === point.index" transition="opacity">
                <div class="value-box">
                  <span class="value">{{point.value}}</span><span class="unit">{{externalPoints[selectedPathIndex].unit}}</span>
                </div>
                <i class="triangle"></i>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="x-coordinate-box">
        <div class="x-coordinate">
          <div class="x-text" v-for="xCoordinate in xCoordinates" track-by="$index" :style="'width:' + xCoordinatePointsWidth + 'px;'" @click="selectedPointEvent($index)" :class="{'selected': selectedPointIndex === $index}">
            <span :style="selectedPointIndex === $index?('color:' + selectedTextColor):''">{{xCoordinate}}</span>
          </div>
        </div>
      </div>
    </div>
    <div class="legend-box">
      <div class="legend">
        <span v-for="externalPoint in externalPoints" :style="selectedPathIndex === $index?('color:' + externalPoint.color): ''" @touchend="selectedPathEvent($index)" :class="{'selected': selectedPathIndex === $index}"><i :style="'color:' + externalPoint.color + ';background-color:' + externalPoint.color"></i>{{externalPoint.name}}</span>
      </div>
    </div>
  </div>
</template>

<script>
  module.exports = {
    props: {
      // 可视区横轴显示多少个点
      showPointsCount: {
        type: Number,
        default: 4.5
      },
      // 横坐标
      xCoordinates: {
        type: Array,
        default () {
          return ['横轴1', '横轴2', '横轴3', '横轴4', '横轴5', '横轴6', '横轴7', '横轴8', '横轴9', '横轴10']
        }
      },
      // 用于渲染的每一条数据
      points: {
        type: Array,
        default () {
          return []
        }
      },
      // 选中时候显示的颜色
      selectedTextColor: {
        type: String,
        default: '#000'
      }
    },
    data () {
      return {
        svgTopBlank: 0.3, // 图表上下的空白占比
        svgBottomBlank: 0.2, // 图表上下的空白占比
        boxWidth: 500, // 存放当前页面的宽度
        chartHeight: 500, // 存放当图表的高度
        selectedPathIndex: 0, // 已选择的路径的索引
        selectedPointIndex: -1, // 已选择的点的索引
        externalPoints: [ // 用于渲染的点的集合  外部传入的数据格式如下
          {
            name: '名字1',
            unit: 'kg',
            color: 'pink',
            points: [-1, 8, 6, 2, -9, -5, -8, -13, -8, -3]
          },
          // {
          //   name: '名字2',
          //   unit: 'mlllllll',
          //   color: '#ff0',
          //   points: [-9, 5, 8, 13, 8, 4, 6, 3, 1, 8]
          // },
          // {
          //   name: '名字3',
          //   unit: 'mmml',
          //   color: '#f00',
          //   points: [8, 5, 3, -1, 3, 8, -4, 6, 9, 2]
          // },
          {
            name: '名字4',
            unit: 'ml',
            color: '#0ff',
            points: [3, -8, 4, -6, 9, -2, -8, 5, -3]
          }
        ]
      }
    },
    computed: {
      /**
       * computed 计算横坐标每个值的宽度
       * @return {[type]} [description]
       */
      xCoordinatePointsWidth () {
        return this.boxWidth / this.showPointsCount
      },
      /**
       * computed 计算当前图表的总宽度
       * @return {[type]} [description]
       */
      chartBoxWidth () {
        return this.xCoordinatePointsWidth * this.xCoordinates.length
      },
      /**
       * computed 每个点的坐标
       * @return {[type]} [description]
       */
      pointCoordinates () {
        var result = []
        // var count = this.xCoordinates.length
        // var chartBoxWidth = this.chartBoxWidth
        var chartHeight = this.chartHeight // 图表高度
        var xCoordinatePointsWidth = this.xCoordinatePointsWidth // 横坐标每个点的宽度
        var sortArr = [] // 用于排序的当前的点的数组
        this.externalPoints.forEach((item, index) => {
          item.points.map((item) => {
            if (item - 0 > 0) {
              sortArr.push(item)
            }
          })
        })
        sortArr.sort((x, y) => {
          return x - y
        })
        var top = chartHeight * this.svgTopBlank // 曲线的最高点
        var bottom = chartHeight * (1 - this.svgTopBlank) // 曲线的最低点
        var dHeight = chartHeight * (1 - (this.svgTopBlank + this.svgBottomBlank)) // 曲线的高度差
        var minNum = sortArr[0] // 最小数
        var maxNum = sortArr[sortArr.length - 1] // 最大数
        var dNum = maxNum - minNum // 最小数和最大数的差值
        this.externalPoints.forEach((itemArr, index1) => {
          result[index1] = []
          itemArr.points.forEach((item, index2) => {
            if (item > 0) {
              var obj = {}
              obj.x = xCoordinatePointsWidth / 2 + xCoordinatePointsWidth * index2
              obj.y = computedY(item)
              obj.index = index2
              obj.parentIndex = index1
              obj.value = item
              result[index1].push(obj)
            }
          })
        })
        return result
        function computedY (num) { // 计算每个点的纵坐标
          let y = 0
          if (dNum > 0) {
            y = parseInt((top + (maxNum - num) / dNum * dHeight) * 100) / 100
          } else {
            y = (top + bottom) / 2
          }
          return y
        }
      },

      /**
       * computed 用于渲染svg的path的d属性的值
       * @return {[type]} [description]
       */
      paths () {
        var result = []
        this.pointCoordinates.forEach((item, index) => {
          if (item.length > 1) {
            var path = ''
            path += 'M' + item[0].x + ' ' + item[0].y + 'L'
            for (let i = 1, length = item.length; i < length; i++) {
              path += ' ' + item[i].x + ' ' + item[i].y
            }
            result.push(path)
          } else {
            result.push('')
          }
        })
        return result
      },

      /**
       * computed已选择的路径的各个坐标点
       * @return {[type]} [description]
       */
      selectedPathCoordinates () {
        return this.pointCoordinates[this.selectedPathIndex]
      }
    },

    ready () {
      this.initViews() // 初始化
    },

    methods: {
      /**
       * 选择当前曲线
       * @param  {[type]} index [description]
       * @return {[type]}       [description]
       */
      selectedPathEvent (index) {
        this.selectedPointIndex = -1
        this.selectedPathIndex = index
      },

      /**
       * 选择当前点
       * @param  {[type]} index [description]
       * @return {[type]}       [description]
       */
      selectedPointEvent (index) {
        this.selectedPointIndex = index
      },
      /**
       * 总初始化
       * @return {[type]} [description]
       */
      initViews () {
        // 获取当前图表宽度
        this.boxWidth = this.$el.clientWidth
        this.chartHeight = this.$el.children[0].children[0].children[0].clientHeight
        this.checkPointsLength() // 检查当前传入的数值是否正确
      },
      /**
       * 检查当前传入的数值是否正确
       * @return {[type]} [description]
       */
      checkPointsLength () {
        var result = true
        if (this.points.length) {
          this.externalPoints = this.points
        }
        this.externalPoints.map((item) => {
          if (this.xCoordinates.length !== item.points.length) {
            result = false
            console.warn(item.name + '的数据长度和横坐标的个数不一致， ' + item.name + ' 只有 ' + item.points.length + ' 个数，但是横坐标的长度是 ' + this.xCoordinates.length + ' ，如果中间的某个点不存在，请用 -1 占位')
            var length = this.xCoordinates.length - item.points.length
            var arr = []
            for (let i = 0; i < length; i++) {
              arr.push(-1)
            }
            item.points = item.points.concat(arr)
          }
        })
        return result
      },

      /**
       * 计算当前path的颜色
       * @param  {[type]} pointCoordinate [description]
       * @return {[type]}                 [description]
       */
      pathColor (pointCoordinate) {
        var index = this.pointCoordinates.indexOf(pointCoordinate)
        return this.externalPoints[index].color
      }
    }
  }

</script>

<style lang="stylus">
  @import '../assets/style/common'
  .compoents-chart-box
    width 100%
    height 100%
    overflow auto
    -webkit-overflow-scrolling touch
    background rgba(0,0,0,0.3)
    position relative
    .view-box
      height 100%
      position relative
      .svg-chart-box
        width 100%
        height 100%
        padding-bottom 1.6rem
        box-sizing border-box
        position relative
        svg
          perspective 1000px
          path
            stroke-linecap round
            stroke-width 5
            fill none
            opacity 0.3
          .selected
            path
              stroke-width 8
              opacity 1
          .circle
            opacity 0.2
        .points-box
          .point-touch
            position absolute
            width 1rem
            height 1rem
            transition all ease 0.3s
            transform translate3d(-50%, -50%, 0)
            .point
              position absolute
              top 50%
              left 50%
              width 0.3rem
              height 0.3rem
              border-radius 50%
              transform translate3d(-50%, -50%, 0)
              .triangle
                content " "
                display block
                position absolute
                bottom 180%
                left 50%
                transform translate3d(-50%, 0.19rem, 0)
                width 0
                height 0
                border-top 0.2rem solid rgba(0,0,0,0.8)
                border-left 0.2rem solid transparent
                border-right 0.2rem solid transparent
              .value-box
                position absolute
                bottom 180%
                left 50%
                transform translate3d(-50%, 0, 0)
                background rgba(0,0,0,0.8)
                color #fff
                white-space nowrap
                padding 0.1rem 0.2rem
                border-radius 0.2rem
          .selected
            .point
              transition all ease 0.2s
              width 0.45rem
              height 0.45rem

      .x-coordinate-box
        width 100%
        height 0.8rem
        position absolute
        bottom 0.8rem
        left 0
        .x-coordinate
          height 100%
          box-sizing border-box
          border-top 0.03rem solid #fff
          border-bottom 0.03rem solid #fff
          line-height 0.74rem
          white-space nowrap
          .x-text
            display inline-block
            height 100%
            text-align center
            white-space nowrap
            text-overflow ellipsis
            width 100%
            span
              margin 0 auto
              padding 5% 10%
            &.selected
              span
                background #fff
                color #000 // 根据实际需要去改动
  .legend-box
    height 0.8rem
    width 100%
    position absolute
    bottom 0
    left 0
    .legend
      display inline-block
      line-height 0.8rem
      span
        text-align center
        padding 0 0.5rem
        color #fff
        i
          display inline-block
          width 0.2rem
          height 0.2rem
          border-radius 50%
          margin-right 0.1rem


</style>
